<?php

/**
 * 购物流程
 */

define('IN_ECS', true);
require(dirname(__FILE__) . '/includes/init.php');
 require(ROOT_PATH . 'includes/lib_order.php');
/* 载入语言文件 */
// require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/user.php');
// require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/shopping_flow.php');
/*------------------------------------------------------ */
//-- INPUT
/*------------------------------------------------------ */
if (!isset($_REQUEST['step']))
{
    $_REQUEST['step'] = "cart";
}

// 判断STEP参数是否在允许范围内
$is_stpe=array( 'exchange', 'add_to_cart' ,'add_to_cart_pigment','checkout','select_shipping','select_payment','change_integral','change_bonus','check_integral','done','clear','validate_bonus','follow_cart','dropGoods','updateCart','cart');
if (!in_array($_REQUEST['step'], $is_stpe))
{
	errorMsg('请求错误');
}

// 购物车页面
if($_REQUEST['step'] == 'cart')
{
    /* 标记购物流程为普通商品 */
    $_SESSION['flow_type'] = CART_GENERAL_GOODS;

    /* 取得商品列表，计算合计 */
    $cart_goods = cart_goods($_SESSION['flow_type']);
    
    var_dump($cart_goods);

    /* 取得刮刮乐商品列表，计算合计 */
    $user_id= $_SESSION['user_id'];
    if(!empty($user_id)){
    $sql ="SELECT g.goods_name,g.goods_thumb, ge.exchange ,ge.cdkey FROM ".$GLOBALS['ecs']->table('goods')." AS g ".
          "LEFT JOIN ".$GLOBALS['ecs']->table('guadanle')." AS ge ".
          "ON g.goods_sku = ge.goods_sku ".
          "WHERE ge.user_id = '$user_id' AND ge.exchange='1'";
    $exchange_goods=$db->getALL($sql);
    }
    /* 计算费用 */
    $totalfee = 0;
    foreach ($cart_goods as $row) {
        $totalfee += $row['subtotal'];
    }
    echo $totalfee;   
}

/**
 * 修改购物车商品数量 
 * 商品数量、rec_id（购物车的商品记录ID）
 */
elseif ($_REQUEST['step'] == 'updateCart')
{   
    if (isset($_REQUEST['number']) && isset($_REQUEST['recId']))
    {
        if(!flow_update_cart(array($_REQUEST['recId'] => $_REQUEST['number']))){
            errorMsg('库存量不足');
        }else{
            /* 修改成功 */
            $response = array('response' => 'updateCart');
            echo json_encode($response);
            exit;
        }
    }
}

/*------------------------------------------------------ */
//-- 删除购物车中的商品
/*------------------------------------------------------ */

elseif ($_REQUEST['step'] == 'dropGoods')
{
    
        $rec_id = intval($_REQUEST['recId']);
        flow_drop_cart_goods($rec_id);
        /* 删除成功 */
        $response = array('response' => 'dropGoods');
        echo json_encode($response);
        exit;
}


/**
 * 更新购物车中的商品数量
 *
 * @access  public
 * @param   array   $arr
 * @return  void
 */
function flow_update_cart($arr)
{
    /* 处理 */
    foreach ($arr AS $key => $val)
    {

        $val = intval(make_semiangle($val));    //将字符全部转换为半角字符
        //查询：
        $sql = "SELECT gs.goods_number AS goods_stock, c.goods_id, c.goods_attr_id, c.product_id, c.extension_code FROM " .$GLOBALS['ecs']->table('cart').
               " c LEFT JOIN " . $GLOBALS['ecs']->table('goods_stock') . " gs ON(gs.goods_id = c.goods_id AND gs.goods_attr_id = c.goods_attr_id AND gs.area_id = c.area_id) ".
               " WHERE c.rec_id='$key' AND c.session_id='" . SESS_ID . "'";
        $goods = $GLOBALS['db']->getRow($sql);

        //订货数量大于0
        if ($val > 0)
        {
            if($val <= $goods['goods_stock'])
            {
                $attr_id    = empty($goods['goods_attr_id']) ? array() : explode(',', $goods['goods_attr_id']);
                $goods_price = get_final_price($goods['goods_id'], $val, true, $attr_id);

                //更新购物车中的商品数量
                if($goods_price){
                    $sql = "UPDATE " .$GLOBALS['ecs']->table('cart').
                            " SET goods_number = '$val', goods_price = '$goods_price' WHERE rec_id='$key' AND session_id='" . SESS_ID . "'";
                }else{
                    $sql = "UPDATE " .$GLOBALS['ecs']->table('cart').
                            " SET goods_number = '$val' WHERE rec_id='$key' AND session_id='" . SESS_ID . "'";
                }
            }
            else  //修改数量超过库存
            {
                return false;
            }
        }
        //订货数量等于0
        else
        {
            $sql = "DELETE FROM " .$GLOBALS['ecs']->table('cart').
                " WHERE rec_id='$key' AND session_id='" .SESS_ID. "'";
        }
        $GLOBALS['db']->query($sql);
    }
    return true; 
}

/**
 * 删除购物车中的商品
 *
 * @access  public
 * @param   integer $id
 * @return  void
 */
function flow_drop_cart_goods($id)
{
    /* 取得商品id */
    $sql = "SELECT * FROM " .$GLOBALS['ecs']->table('cart'). " WHERE rec_id = '$id'";
    $row = $GLOBALS['db']->getRow($sql);
    if ($row)
    {
        //如果是超值礼包
        if ($row['extension_code'] == 'package_buy')
        {
            $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') .
                    " WHERE session_id = '" . SESS_ID . "' " .
                    "AND rec_id = '$id' LIMIT 1";
        }

        //如果是普通商品，同时删除所有赠品及其配件
        elseif ($row['parent_id'] == 0 && $row['is_gift'] == 0)
        {
            /* 检查购物车中该普通商品的不可单独销售的配件并删除 */
            $sql = "SELECT c.rec_id
                    FROM " . $GLOBALS['ecs']->table('cart') . " AS c, " . $GLOBALS['ecs']->table('group_goods') . " AS gg, " . $GLOBALS['ecs']->table('goods'). " AS g
                    WHERE gg.parent_id = '" . $row['goods_id'] . "'
                    AND c.goods_id = gg.goods_id
                    AND c.parent_id = '" . $row['goods_id'] . "'
                    AND c.extension_code <> 'package_buy'
                    AND gg.goods_id = g.goods_id
                    AND g.is_alone_sale = 0";
            $res = $GLOBALS['db']->query($sql);
            $_del_str = $id . ',';
            while ($id_alone_sale_goods = $GLOBALS['db']->fetchRow($res))
            {
                $_del_str .= $id_alone_sale_goods['rec_id'] . ',';
            }
            $_del_str = trim($_del_str, ',');

            $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') .
                    " WHERE (session_id = '" . SESS_ID . "'" . ($_SESSION['user_id']?" OR user_id = $_SESSION[user_id]":'') . ")" .
                    " AND (rec_id IN ($_del_str) OR parent_id = '$row[goods_id]' OR is_gift <> 0)";
        }

        //如果不是普通商品，只删除该商品即可
        else
        {
            $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') .
                    " WHERE session_id = '" . SESS_ID . "' " .
                    "AND rec_id = '$id' LIMIT 1";
        }

        $GLOBALS['db']->query($sql);
    }

    flow_clear_cart_alone();
}

/**
 * 删除购物车中不能单独销售的商品
 *
 * @access  public
 * @return  void
 */
function flow_clear_cart_alone()
{
    /* 查询：购物车中所有不可以单独销售的配件 */
    $sql = "SELECT c.rec_id, gg.parent_id
            FROM " . $GLOBALS['ecs']->table('cart') . " AS c
                LEFT JOIN " . $GLOBALS['ecs']->table('group_goods') . " AS gg ON c.goods_id = gg.goods_id
                LEFT JOIN" . $GLOBALS['ecs']->table('goods') . " AS g ON c.goods_id = g.goods_id
            WHERE c.session_id = '" . SESS_ID . "'
            AND c.extension_code <> 'package_buy'
            AND gg.parent_id > 0
            AND g.is_alone_sale = 0";
    $res = $GLOBALS['db']->query($sql);
    $rec_id = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $rec_id[$row['rec_id']][] = $row['parent_id'];
    }

    if (empty($rec_id))
    {
        return;
    }

    /* 查询：购物车中所有商品 */
    $sql = "SELECT DISTINCT goods_id
            FROM " . $GLOBALS['ecs']->table('cart') . "
            WHERE session_id = '" . SESS_ID . "'
            AND extension_code <> 'package_buy'";
    $res = $GLOBALS['db']->query($sql);
    $cart_good = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $cart_good[] = $row['goods_id'];
    }

    if (empty($cart_good))
    {
        return;
    }

    /* 如果购物车中不可以单独销售配件的基本件不存在则删除该配件 */
    $del_rec_id = '';
    foreach ($rec_id as $key => $value)
    {
        foreach ($value as $v)
        {
            if (in_array($v, $cart_good))
            {
                continue 2;
            }
        }

        $del_rec_id = $key . ',';
    }
    $del_rec_id = trim($del_rec_id, ',');

    if ($del_rec_id == '')
    {
        return;
    }

    /* 删除 */
    $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') ."
            WHERE session_id = '" . SESS_ID . "'
            AND rec_id IN ($del_rec_id)";
    $GLOBALS['db']->query($sql);
}